package ConveyorBelt.State;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TileSet;
import org.newdawn.slick.tiled.TiledMapPlus;

import ConveyorBelt.Util.ImageUtil;

public class CreateMap extends BasicGameState{
	public static final int stateID = 8;
	public TiledMapPlus map;
	public TileSet tileset;
	public int mapX, mapY;
	public int mouseX, mouseY;
	public int layerNumber;
	public Image tile = null;
	public Image chosenTile = null;
	
	@Override
	public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
		map = new TiledMapPlus("resources/map/custom_map.tmx");
		mapX = 50;
		mapY = gc.getHeight()/2 - map.getHeight()*map.getTileHeight()/2;
//		System.out.println("Tileset Count: " +map.getTileSetCount());
		tileset = map.getTileSet(0);
//		System.out.println(tileset.imageref);
		tile = new Image(tileset.imageref);
	}

	@Override
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
		ImageUtil.background.draw(0, 0);
		tile.draw(950, mapY);
		map.render(mapX, mapY);
		g.setColor(Color.white);
		for(int tx=0; tx<map.getWidth(); tx++) {
			for(int ty=0; ty<map.getHeight(); ty++) {
				g.drawRect(tx*map.getTileWidth()+mapX, ty*map.getTileHeight()+mapY, map.getTileWidth(), map.getTileHeight());
			}
		}
		g.drawLine(900, 0, 900, 720);
		if(chosenTile != null) {
			chosenTile.drawWarped(1000, 450, 1000, 650, 1200, 650, 1200, 450);
		}
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
		Input input = gc.getInput();
		mouseX = input.getMouseX();
		mouseY = input.getMouseY();
		if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && mouseX >= 950 && mouseX <= (tile.getWidth()+950) &&
				mouseY >= mapY && mouseY <= (mapY + tile.getWidth())) {
			int tx = (int) (mouseX - 950) / 32;
			int ty = (int) (mouseY - mapY) / 32;
			chosenTile = tile.getSubImage(tx*32, ty*32, 32, 32);
		}
	}

	@Override
	public int getID() {
		return stateID;
	}

}
